package com.victor.core.util;

import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.security.InvalidParameterException;

/**
 * 本地文件转pdf
 *
 * @author guokaige
 */
public class PdfUtil {
    private int topValue;
    private int leftValue;
    private int rightValue;
    private int bottomValue;
    private int userSpaceWidth;

    public PdfUtil(int topValue, int leftValue, int rightValue,
                   int bottomValue, int userSpaceWidth) {
        super();
        this.topValue = topValue;
        this.leftValue = leftValue;
        this.rightValue = rightValue;
        this.bottomValue = bottomValue;
        this.userSpaceWidth = userSpaceWidth;
    }

    /**
     * 创建pdf文件
     *
     * @param htmlDocument html代码文档
     * @param outputPath   pdf文件输出路径
     * @param fontPath     字体路径
     * @return
     * @throws InvalidParameterException
     * @throws MalformedURLException
     * @throws IOException
     * @author Jiabin.Zhao
     * @date 创建时间：2017年2月22日 上午11:55:29
     * @version 1.0
     * @parameter
     * @since
     */
    public void createPDFFile(String htmlDocument, String outputPath,
                              String fontPath) throws InvalidParameterException,
            MalformedURLException, IOException {
        PD4ML pd4ml = new PD4ML();
        pd4ml.setHtmlWidth(userSpaceWidth); // set frame width of
        pd4ml.setPageSize(PD4Constants.A4);
        pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));
        pd4ml.addStyle("BODY {margin: 0}", true);
        pd4ml.useTTF(fontPath, true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pd4ml.render(new StringReader(htmlDocument), baos);
        baos.close();
        //System.out.println("resulting PDF size: " + baos.size() + " bytes");
        File output = new File(outputPath);
        // 创建父级目录
        if (!output.getParentFile().exists()) {
            output.getParentFile().mkdirs();
        }
        java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
        fos.write(baos.toByteArray());
        fos.close();
        //System.out.println(outputPath + "\ndone.");
    }

    /**
     * 创建pdf流 不保存文件
     *
     * @param htmlDocument html代码文档
     * @param fontPath     字体路径
     * @param response
     * @return
     * @throws InvalidParameterException
     * @throws MalformedURLException
     * @throws IOException
     * @author Jiabin.Zhao
     * @date 创建时间：2017年2月22日 上午11:56:29
     * @version 1.0
     * @parameter
     * @since
     */
    public void createPDFFileByHttp(String htmlDocument, String fontPath, String statu, String pdfName,
                                    HttpServletResponse response)
            throws InvalidParameterException, MalformedURLException,
            IOException {
        // 状态 statu=1为下载文件 反之为打开文件
        PD4ML pd4ml = new PD4ML();
        pd4ml.setHtmlWidth(userSpaceWidth); // set frame width of
        pd4ml.setPageSize(PD4Constants.A4);
        pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,
                rightValue));
        pd4ml.addStyle("BODY {margin: 0}", true);
        pd4ml.useTTF(fontPath, true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pd4ml.render(new StringReader(htmlDocument), baos);
        baos.close();
        System.out.println("resulting PDF size: " + baos.size() + " bytes");
        // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("application/pdf");
        // 清除首部的空白行。
        response.reset();
        response.setHeader("Cache-Control", "max-age=0");
        if ("1".equals(statu)) {
            String fileName = URLEncoder.encode(pdfName, "UTF-8");
            // 通知浏览器下载文件而不是打开
            response.setHeader("Content-Disposition", new StringBuffer(
                    "attachment; filename=").append(fileName).toString());
        }
        response.setCharacterEncoding("UTF-8");
        OutputStream fos = response.getOutputStream();
        fos.write(baos.toByteArray());
        fos.close();
        System.out.println("done.");
    }

    /**
     * 转码
     *
     * @param path
     * @param encoding
     * @return
     * @throws IOException
     * @Title: title
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @version V2.0
     * @author guokaige
     * @Date 2016-12-7 下午2:54:30
     */
    public final static String readFile(String path, String encoding)
            throws IOException {

        File f = new File(path);
        FileInputStream is = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        byte buffer[] = new byte[2048];

        int read;
        do {
            read = is.read(buffer, 0, buffer.length);
            if (read > 0) {
                fos.write(buffer, 0, read);
            }
        } while (read > -1);

        fos.close();
        bis.close();
        is.close();

        return fos.toString(encoding);
    }

}